﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using System.Data;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ProjectScheduling
{
    public partial class ProjectPreparedPage : UserControl
    {
        public readonly static ProjectPreparedPage b = new();
        private record struct search_datas(int page, int row, int totalpage, List<Projects> list, string key, DateTime start_time, DateTime end_time);
        private search_datas Datas = new(1, 40, 0, [], "", DateTime.MinValue, DateTime.MaxValue);
        private readonly List<Enum_ProjectState> States = [Enum_ProjectState.挂起, Enum_ProjectState.待排期];

        private ProjectPreparedPage()
        {
            InitializeComponent();
            view_data.AutoGenerateColumns = false;
            view_data.AutoSizeRowsMode=DataGridViewAutoSizeRowsMode.AllCells;
            txt_search_pagesize.Text = "40";
            txt_search_pagesize.SelectedIndexChanged += (o, e) =>
            {
                Datas.row = Convert.ToInt32(txt_search_pagesize.Text);
                Search();
            };
            #region 搜索项赋值
            txt_search_key.TextChanged += (o, e) =>
            {
                Datas.key = txt_search_key.Text?.Trim() ?? "";
            };
            txt_search_start.TextChanged += (o, e) =>
            {
                Datas.start_time = txt_search_start.Value;
            };
            txt_search_end.TextChanged += (o, e) =>
            {
                Datas.end_time = txt_search_end.Value;
            };
            #endregion


        }

        private void ProjectPreparedPage_ControlAdded(object sender, ControlEventArgs e)
        {
            Console.WriteLine("组件插入中");
        }
        private void SetPageState()
        {
            btn_page_first.Enabled = Datas.page > 1;
            btn_page_pre.Enabled = Datas.page > 1;
            btn_page_last.Enabled = Datas.page < Datas.totalpage;
            btn_page_next.Enabled = Datas.page < Datas.totalpage;
        }
        private void Init()
        {
            var minTime = ProjectDao.Base.GetMin(it => States.Contains(it.State), it => it.CreateDate);
            var maxTime = ProjectDao.Base.GetMax(it => States.Contains(it.State), it => it.CreateDate);
            if (minTime != DateTime.MinValue)
            {
                txt_search_start.MinDate = minTime;
                txt_search_start.Value = minTime;
                txt_search_end.MinDate = minTime;
            }
            else
            {
                txt_search_start.Enabled = false;
            }
            if (maxTime != DateTime.MinValue)
            {
                txt_search_start.MaxDate = maxTime;
                txt_search_end.MaxDate = maxTime;
                txt_search_end.Value = maxTime;
            }
            else
            {
                txt_search_end.Enabled = false;
            }
            SetPageState();

            Search();
            //Datas.

        }
        private void Search()
        {
            var datas = ProjectDao.Base.FindAll(Datas.page, Datas.row,
                             it =>
                             (string.IsNullOrEmpty(Datas.key) || (it.Name != null && it.Name.Contains(Datas.key))) &&
                            it.CreateDate >= Datas.start_time && it.CreateDate <= Datas.end_time &&
                            States.Contains(it.State)
                            );

            Datas.totalpage = Convert.ToInt32(Math.Ceiling(1m * datas.Total / Datas.row));
            Datas.list = datas.Items ?? [];
            lb_page_msg.Text = $"当前第{Datas.page}页/共{Datas.totalpage}页";
            txt_search_total.Text=datas.Total.ToString();
            SetPageState();
            DataTable table = new();
            void columns(params string[] strs) => strs.ToList().ForEach(it => table.Columns.Add(new DataColumn { ColumnName = it }));
            columns("Id", "Name", "ProjectTypeName", "PlanStartDate", "CreateDate", "CreatorName", "StateStr", "State", "OwnerShip");
            Datas.list.ForEach(item =>
            {
                var row = table.NewRow();
                row["Id"] = item.Id;
                row["Name"] = item.Name;
                row["ProjectTypeName"] = item.ProjectType?.Name?.ToString() ?? "";
                row["PlanStartDate"] = item.PlanStartDate.ToString("yyyy-MM-dd日");
                row["CreateDate"] = item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                row["StateStr"] = item.State.ToString();
                row["State"] = (int)item.State;
                row["CreatorName"] = item.Sales?.TrueName ?? "";
                row["OwnerShip"] = item.OwnerShip ?? "";
                table.Rows.Add(row);
            });
            view_data.DataSource = table;
        }
        private void ProjectPreparedPage_VisibleChanged(object sender, EventArgs e)
        {
            if (sender is Form { Visible: false }) return;
            Init();
        }

        private void ProjectPreparedPage_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void Btn_search_Click(object sender, EventArgs e)
        {
            Datas.page = 1;
            Search();
        }

        private void Btn_page_first_Click(object sender, EventArgs e)
        {
            Datas.page = 1;
            Search();
        }

        private void Btn_page_pre_Click(object sender, EventArgs e)
        {
            Datas.page--;
            Search();
        }

        private void Btn_page_next_Click(object sender, EventArgs e)
        {
            Datas.page++;
            Search();
        }

        private void Btn_page_last_Click(object sender, EventArgs e)
        {
            Datas.page = Datas.totalpage;
            Search();
        }

        private void View_data_SelectionChanged(object sender, EventArgs e)
        {
            view_data.ClearSelection();
        }

        private void Btn_add_Click(object sender, EventArgs e)
        {
            var form = AddProjectPreparedForm.b;
            form.ok_action = Search;
            form.Init(0);
            form.ShowDialog();
        }

        private void View_data_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            var data = Datas.list.ElementAt(e.RowIndex) ?? new();
            var id = Convert.ToInt32(view_data.Rows[e.RowIndex].Cells[0].Value);
            switch (e.ColumnIndex)
            {
                //排期
                case 8:
                    if (data.ApproveState != "暂未审批")
                    {

                        SetPreparedForm.b.action = Search;
                        SetPreparedForm.b.Init(id);
                        SetPreparedForm.b.ShowDialog();
                    }
                    break;
                // 编辑
                case 9:
                    var form = AddProjectPreparedForm.b;
                    form.ok_action = Search;
                    form.Init(id);
                    form.ShowDialog();
                    break;
                // 删除
                case 10:
                    if (MessageBox.Show("是否确定要删除当前项目", "删除确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        ProjectDao.Base.Delete(id);
                        Search();
                        return;
                    }
                    break;
            }
        }

        private void View_data_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (view_data.DataSource is not DataTable dt) return;
            (Color back, Color fore) = Program.GetColorByState(Convert.ToInt32(dt.Rows[e.RowIndex]["State"]));
            DataGridViewCellStyle style = view_data.Rows[e.RowIndex].DefaultCellStyle ?? new DataGridViewCellStyle();
            style.BackColor = back;
            style.ForeColor = fore;
        }

        private void view_data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0) return;
            try
            {
                var data = Datas.list.ElementAt(e.RowIndex);
                if (data == null) return;
                if (data.ApproveState == "暂未审批" && e.ColumnIndex == 8)
                {
                    e.Value = "";
                    var dg = view_data[8, e.RowIndex];
                    dg.Style.BackColor = Color.White;
                }
            }
            catch (Exception)
            {

            }
        }
    }
}